import os
import random

import numpy as np
import scipy.io
import matplotlib.pyplot as plt


def split_joint(y:np.array, period:float, rate:float=0.88) -> np.array:
    """
    周期拼接
    """
    y_true = np.copy(y)
    correction = 0
    for i in range(1, len(y)):
        diff = y[i] - y[i-1]

        if abs(diff) > period*rate:
            if diff > 0:
                correction -= period
            else:
               correction += period
        y_true[i] += correction
    return y_true


def delt(y:np.array) -> np.array:
    """
    上下差值
    """
    y_delt = np.zeros(y.shape)
    for i in range(1, len(y)):
        diff = y[i] - y[i-1]
        y_delt[i] = diff
    return y_delt


def test():
    # Simulate a signal
    np.random.seed(42)
    x = np.linspace(0.3, 0.6, 200)
    y_ori = 10 * np.sin(2 * np.pi * 5 * x) + 5 * x
    period = 6
    y_wrapped = y_ori % period - 3


    # Unwrap the signal
    y_unwrapped = split_joint(y_wrapped, period)

    # Plotting
    plt.figure(figsize=(12, 6))

    plt.subplot(1, 2, 1)
    plt.scatter(x, y_wrapped, label='Ori Signal (Scatter)', s=5)  # Plot as scatter
    plt.xlabel('Time')
    plt.title('ori signal')
    plt.legend()

    plt.subplot(1, 2, 2)
    plt.plot(x, y_unwrapped, label='Dealed Signal')
    plt.xlabel('Time')
    plt.title('dealed signal')
    plt.legend()

    plt.tight_layout()
    plt.show()


def deal_hcn_data(file_name:str):
    data = scipy.io.loadmat(file_name)
    # faixx  nexx
    period = 8

    indexs = random.sample(range(1,51), 4)
    # indexs = [3,9,49]
    # indexs = range(1,51)
    for ii in indexs:
        plt.figure(figsize=(12, 9))
        plt.subplot(3, 1, 1)
        plt.scatter(range(len(data[f'fai{ii}'])),data[f'fai{ii}'], label=f'fai{ii}', s=1)
        plt.title('ori signal')
        plt.legend()

        # plt.subplot(3, 1, 2)
        # plt.plot(data[f'ne{ii}'], label=f'ne{ii}')
        # plt.title('true signal')
        # plt.legend()

        plt.subplot(3, 1, 2)
        y_delt = delt(data[f'fai{ii}'])
        plt.plot(y_delt, label=f'y_delt {ii}')
        plt.title('y_delt')
        plt.legend()

        plt.subplot(3, 1, 3)
        plt.plot(data[f'ne{ii}'], label=f'ne{ii}')
        # y_deal = split_joint(data[f'fai{ii}'],period,rate=0.6)/8*33
        # plt.plot(y_deal, label=f'dealed ne{ii}')
        # plt.title('dealed signal')
        plt.legend()

        plt.tight_layout()
        plt.show()
        # plt.savefig(os.path.join('results99',f'{ii}.png'))
        # print(f'{ii} done!')
        # plt.close()

def mdsdata():
    import MDSplus
    tree = MDSplus.Tree('exl50u', 9381, path='192.168.20.11::/media/ennfusion/trees/exl50u')
    data = tree.getNode(r'\TEMP01').data()
    plt.figure(figsize=(12, 9))
    plt.subplot(3, 1, 1)
    plt.scatter(range(len(data)),data, label=f'fai9381', s=1)
    plt.title('ori signal')
    plt.legend()

    plt.subplot(3, 1, 2)
    ne = tree.getNode(r'\HCN_NE001').data()
    plt.plot(ne, label=f'ne9381')
    plt.title('true signal')
    plt.legend()

    plt.subplot(3, 1, 3)
    plt.plot(ne, label=f'ne9381')
    y_deal = split_joint(data,8.0,0.5)/8*33
    plt.plot(y_deal, label=f'dealed fai')
    plt.title('dealed signal')
    plt.legend()

    plt.tight_layout()
    plt.show()



if __name__=='__main__':
    # test()
    file_name = 'sjj1.mat'
    deal_hcn_data(file_name)
    # mdsdata()
    print('Done!')
